package com.kedacom.demo.hmac;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HMACFilter implements Filter {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

		String httpMethod = httpRequest.getMethod();
		String contentMd5 = httpRequest.getHeader("Content-Md5");
		String contentType = httpRequest.getContentType();
		String date = httpRequest.getHeader("Date");
		String requestURI = httpRequest.getRequestURI();

		String requestHMAC = httpRequest.getHeader("hmac");
		logger.debug("request hmac is: {}", requestHMAC);

		String toSign = httpMethod + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + requestURI;
		String hmac = HMACUtils.calculateHMAC("888", toSign);
		logger.debug("hmac is: {}", hmac);

		logger.debug(hmac.equals(requestHMAC.substring(requestHMAC.indexOf(":") + 1)) ? "hmac equals"
				: "hmac does not equal");

		filterChain.doFilter(httpRequest, httpResponse);
	}

	@Override
	public void destroy() {
	}

}
